import local from "@/utils/local";
import { useEffect } from "react";
import type { ReactNode } from "react";
import { useNavigate } from "react-router-dom";
import type { NavigateFunction } from "react-router-dom";
import { setUserInfo } from "@/store/app/appSlice";
import { useAppDispatch, useAppSelector } from "@/store/hooks";

export default function Auth({
  children,
}: Readonly<{
  children: ReactNode;
}>) {
  const { userInfo } = useAppSelector((state) => state.app);
  const dispatch = useAppDispatch();
  const navigate: NavigateFunction = useNavigate();

  useEffect(() => {
    if (!userInfo) {
      const localUserInfo:any = local.get("userInfo");
      if (localUserInfo) {
        dispatch(setUserInfo(localUserInfo));
      } else {
        navigate("/login", { replace: true });
      }
    }
  }, []);
  return userInfo ? children : null;
}
